import React, { Component } from 'react';
import {
  Row,
  Col,
  Input,
  Select,
  Button,
  message,
  Form,
  Icon,
  Table,
  Pagination,
  Modal,
  Radio,
  Cascader,
  Tooltip,
  Spin,
} from 'antd';
import moment from 'moment';
// 网络请求
import { getUsersByTypePage } from '@/services/users/getUsersByTypePage';
import { getUsersByTypeAndChar } from '@/services/users/getUsersByTypeAndChar';
import { delUserdata } from '@/services/users/delUserdata';
import { upUserdata } from '@/services/users/upUserdata';
import { addUserdata } from '@/services/users/addUserdata';
import { getAllClasses } from '@/services/admin/getAllClasses';

const { Option } = Select;
import './index.less';
import cityData from '@/assets/js/city';
class Student extends Component {
  state = {
    // 关键字列表
    charTypeList: [
      { value: 'username', label: '姓名' },
      { value: 'address', label: '地址' },
      { value: 'id', label: '学号' },
      { value: 'classes', label: '班级' },
    ],
    //页码和页数
    queryInfo: {
      pagesize: 5,
      pagenum: 1,
    },
    dataSource: [], // 学生数据
    allStudentNum: undefined, //学生数量
    addStudentVisible: false, // 添加学生模态框
    allClasses: [], //所有班级
    selectedRows: [], //表格选择的项目
  };
  // 渲染规则
  columns = [
    {
      title: '学号',
      dataIndex: 'id',
      key: 'id',
      fixed: 'left',
      sorter: (a, b) => a.id - b.id,
      sortDirections: ['descend'],
      width: 100,
    },
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username',
      sorter: (a, b) => a.username.localeCompare(b.username, 'zh'),
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      filters: [
        {
          text: '男',
          value: '男',
        },
        {
          text: '女',
          value: '女',
        },
      ],
      onFilter: (value, record) => record.sex.indexOf(value) === 0,
    },
    {
      title: '生源地',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '班级',
      dataIndex: 'classes',
      key: 'classes',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: () => {
        return '学生';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      // sorter: (a, b) => a.create_time.localeCompare(b.create_time,'zh'),
      sorter: (a, b) => (a.create_time < b.create_time ? -1 : 1),
      render: (text) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss');
      },
      defaultSortOrder: 'descend',
      sortDirections: [],
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'password',
      width: 180,
      render: (text) => {
        return moment(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'update_time',
      width: 250,
      fixed: 'right',
      render: (id) => {
        return (
          <div>
            <Button type="primary" icon="edit">
              编辑
            </Button>
            <Tooltip title="删除不可逆!!" placement="right">
              <Button
                type="danger"
                style={{ marginLeft: 20 }}
                icon="delete"
                onClick={() => this.deleteConfirm(id)}
                disabled={id === 100}
              >
                删除
              </Button>
            </Tooltip>
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.getUsersByTypePage(); // 获取所有学生信息
    this.getAllClasses(); //获取所有班级
  }

  // 获取所有学生信息
  getUsersByTypePage = async () => {
    let res = await getUsersByTypePage(
      2,
      this.state.queryInfo.pagesize,
      this.state.queryInfo.pagenum,
    );
    const dataSource = res.data;
    dataSource.map((item, index) => (item.key = index));
    this.setState({
      dataSource,
      allStudentNum: res.total,
    });
    // message.destroy();
    message.success('获取学生列表成功');
  };

  // 获取有班级
  getAllClasses = async () => {
    const res = await getAllClasses();
    this.setState({
      allClasses: res,
    });
  };

  // 提交搜索
  submitSearch = () => {
    this.props.form.validateFields(
      ['inputText', 'charType'],
      async (err, values) => {
        const { queryInfo } = this.state;
        if (!err) {
          this.setState({ queryInfo: { ...queryInfo, pagenum: 1 } }, () => {
            this.getUsersByTypeAndChar(values);
          });
        } else {
          message.destroy();
          message.error('请填写完整的信息！');
        }
      },
    );
  };

  // 重置
  resetFields = () => {
    this.props.form.resetFields();
    this.setState(
      {
        queryInfo: {
          pagesize: 5,
          pagenum: 1,
        },
      },
      () => {
        this.getUsersByTypePage();
      },
    );
  };

  // 根据关键字查找用户
  getUsersByTypeAndChar = async ({ inputText, charType }) => {
    let res = await getUsersByTypeAndChar(
      2,
      inputText,
      charType,
      this.state.queryInfo.pagesize,
      this.state.queryInfo.pagenum,
    );
    const dataSource = res.data;
    dataSource.map((item, index) => (item.key = index));
    this.setState({
      dataSource,
      allStudentNum: res.total,
    });
    message.destroy();
    message.success('获取学生列表成功');
  };

  // 页码或页大小改变
  pageSizeAndNumChange = async (pagenum, pagesize) => {
    await this.setState({ queryInfo: { pagenum, pagesize } });
    const values = this.props.form.getFieldsValue();
    console.log(values);
    if (!values.inputText) {
      console.log('noInput');
      await this.getUsersByTypePage();
    } else {
      await this.getUsersByTypeAndChar(values);
    }
  };

  // 删除确认框
  deleteConfirm = (id) => {
    Modal.confirm({
      title: '提示',
      content: '此操作将永久删除该用户, 是否继续?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.handleDelete(id);
      },
    });
  };

  // 删除学生
  handleDelete = async (id) => {
    const res = await delUserdata(id);

    message.destroy();
    message.success('删除用户成功');

    this.getUsersByTypePage();
  };

  // 切换添加学生模态框
  setModal2Visible(addStudentVisible) {
    this.setState({ addStudentVisible });
  }

  // 添加学生
  addStudent = () => {
    const { validateFields, resetFields } = this.props.form;
    validateFields(
      ['id', 'username', 'password', 'sex', 'address', 'classes'],
      async (err, values) => {
        values.address = values.address.slice(0, 2).join('');
        values.type ??= 2;
        if (!err) {
          const res = await addUserdata(values);
          if (res === '添加用户成功') {
            message.success('添加学生成功');

            resetFields();
            this.setState({ queryInfo: { pagesize: 5, pagenum: 1 } });
            this.getUsersByTypePage();
          } else {
            message.info(res);
          }
          this.setModal2Visible(false);
        } else {
          message.destroy();
          message.warning('请填写完整的信息后再提交');
        }
      },
    );
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    // 表格多选框
    const rowSelection = {
      onChange: async (_, selectedRows) => {
        await this.setState({ selectedRows });
        console.log(this.state.selectedRows); //可以处理选中的列
      },
      getCheckboxProps: (record) => ({
        disabled: record.username === '曾瑞涪', // Column configuration not to be checked
      }),
      setRowClassName: (record) => 'selected-row-style',
    };

    return (
      <Spin spinning={this.state.allStudentNum === undefined}>
        <div className="student-manage">
          {/* 顶部搜索添加区域 */}
          <Row type="flex">
            <Col span={8}>
              <Form layout="inline" onSubmit={this.handleSubmit}>
                <Form.Item>
                  {getFieldDecorator('charType', {
                    rules: [{ required: true, message: ' ' }],
                  })(
                    <Select style={{ width: 100 }}>
                      <Option value="username">姓名</Option>
                      <Option value="address">地址</Option>
                      <Option value="id">学号</Option>
                      <Option value="classes">班级</Option>
                    </Select>,
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('inputText', {
                    rules: [{ required: true, message: ' ' }],
                  })(
                    <Input
                      placeholder="请输入内容"
                      prefix={<Icon type="search" />}
                      onPressEnter={(e) => {
                        e.preventDefault();
                        document.querySelector('#inputText22')?.focus();
                      }}
                    />,
                  )}
                </Form.Item>
              </Form>
            </Col>

            <Col span={4} pull={1}>
              <Button type="primary" onClick={this.submitSearch}>
                搜索
              </Button>
              <Button
                type="primary"
                onClick={this.resetFields}
                style={{ marginLeft: '20px' }}
              >
                重置
              </Button>
            </Col>

            <Col push={10} span={2}>
              <Button
                type="primary"
                onClick={() => this.setModal2Visible(true)}
                icon="user-add"
              >
                添加学生
              </Button>
            </Col>
          </Row>
          {/* 学生数据表格 */}
          <Table
            dataSource={this.state.dataSource}
            // dataSource={[]}
            className="student-table"
            columns={this.columns}
            style={{ marginTop: 30 }}
            pagination={false}
            scroll={{ x: 1500, y: 380 }}
            rowSelection={rowSelection}
            rowClassName={this.setRowClassName}
            bordered
            locale={{ filterConfirm: 'Ok~', filterReset: 'Reset~' }}
          />

          {/* 分页器 */}
          <Pagination
            showSizeChanger
            showQuickJumper
            total={this.state.allStudentNum}
            pageSize={this.state.queryInfo.pagesize}
            pageSizeOptions={['5', '10', '50', '100']}
            // pageSize={this.state.queryInfo.pagesize}
            onChange={this.pageSizeAndNumChange}
            onShowSizeChange={(_, pageSize) =>
              this.pageSizeAndNumChange(1, pageSize)
            }
          />
          {/* 添加学生模态框 */}
          <Modal
            title="添加学生"
            centered
            visible={this.state.addStudentVisible}
            onOk={this.addStudent}
            onCancel={() => this.setModal2Visible(false)}
            className="add-student-modal"
          >
            <Form layout="inline">
              <Form.Item label="学号">
                {getFieldDecorator('id', {
                  rules: [{ required: true, message: '学号不能为空' }],
                })(
                  <Input
                    placeholder="请输入学号"
                    prefix={<Icon type="trademark" />}
                  />,
                )}
              </Form.Item>
              <Form.Item label="姓名">
                {getFieldDecorator('username', {
                  rules: [{ required: true, message: '姓名不能为空' }],
                })(
                  <Input
                    placeholder="请输入用户名"
                    prefix={<Icon type="user" />}
                  />,
                )}
              </Form.Item>
              <Form.Item label="密码">
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: '密码不能为空' }],
                })(
                  <Input
                    placeholder="请输入密码"
                    prefix={<Icon type="key" />}
                  />,
                )}
              </Form.Item>
              <Form.Item label="性别">
                {getFieldDecorator('sex', {
                  rules: [{ required: true, message: '性别不能为空' }],
                })(
                  <Radio.Group>
                    <Radio value="男">男</Radio>
                    <Radio value="女">女</Radio>
                  </Radio.Group>,
                )}
              </Form.Item>
              <Form.Item label="地址">
                {getFieldDecorator('address', {
                  rules: [{ required: true, message: '地址不能为空' }],
                })(
                  <Cascader
                    options={cityData}
                    placeholder="请选择地址"
                    showSearch={{
                      filter: (inputValue, path) => {
                        console.log(path);
                        return path.some((option) =>
                          option.label
                            .toLowerCase()
                            .includes(inputValue.toLowerCase()),
                        );
                      },
                    }}
                  />,
                )}
              </Form.Item>
              <Form.Item label="班级">
                {getFieldDecorator('classes', {
                  rules: [{ required: true, message: '班级不能为空' }],
                })(
                  <Select
                    style={{ width: '200px' }}
                    placeholder="请选择班级"
                    showSearch
                    filterOption={(input, option) => {
                      return option.props.children
                        .toLowerCase()
                        .includes(input.toLowerCase());
                    }}
                  >
                    {this.state.allClasses.map((item) => {
                      return (
                        <Select.Option key={item.c_id} value={item.class}>
                          {item.class}
                        </Select.Option>
                      );
                    })}
                  </Select>,
                )}
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </Spin>
    );
  }
}

const StudentForm = Form.create({})(Student);
export default StudentForm;
